package edu.ynu.MyProject.service;

import edu.ynu.MyProject.common.service.LogicService;
import edu.ynu.MyProject.dao.IEquipmentDAO;
import edu.ynu.MyProject.dao.IGreenHouseDAO;
import edu.ynu.MyProject.dto.EquipmentDTO;
import edu.ynu.MyProject.dto.GreenHouseDTO;
import edu.ynu.MyProject.entity.Equipment;
import edu.ynu.MyProject.entity.GreenHouseInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class GreenHouseService extends LogicService<IGreenHouseDAO, GreenHouseInfo, Long> {
    public GreenHouseService(IGreenHouseDAO iGreenHouseDAO) {
        super(iGreenHouseDAO);
    }

    @Autowired
    private IEquipmentDAO iEquipmentDAO;

    public GreenHouseDTO getInfo(Long greenhouseId) {
        // 查询大棚信息
        GreenHouseInfo greenhouse = dao.findById(greenhouseId).orElseThrow(() -> new RuntimeException("Greenhouse not found"));
        // 查询设备列表
        List<Equipment> devices = iEquipmentDAO.findByGreenhouseId(greenhouseId);
        // 映射到 DeviceDTO 列表
        List<EquipmentDTO> deviceDTOs = devices.stream()
                .map(equipment -> new EquipmentDTO(equipment.getName(),equipment.getId(),equipment.getType()))
                .collect(Collectors.toList());
        // 创建 GreenhouseDTO 并返回
        return new GreenHouseDTO(greenhouse.getId(), greenhouse.getName(), devices.size(), deviceDTOs);
    }

    public List<List<Object>> getAllDevices(Long greenhouseId) {
        // 查询设备列表
        List<Equipment> equipments = iEquipmentDAO.findByGreenhouseId(greenhouseId);

        // 生成DTO列表
        List<EquipmentDTO> DTOs = equipments.stream()
                .map(device -> new EquipmentDTO(device.getName(), device.getId(), device.getType()))
                .collect(Collectors.toList());

//        生成最终列表
        List<List<Object>> devices = new ArrayList<>();
        for (EquipmentDTO DTO : DTOs) {
            List<Object> list = new ArrayList<>();
            list.add(DTO.getId());
            list.add(DTO.getName());
            list.add(DTO.getType());
            devices.add(list);
        }
        return devices;
    }
}
